<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $account = $request->input('account');
        $password = $request->input('password');
        $field = preg_match('/^\d{11}/', $account) ? 'mobile' : (
            filter_var($account, FILTER_VALIDATE_EMAIL) ? 'email' : 'username'
        );
        $request->validate([
            'account' => ['required', 'exists:users,' . $field],
            'password' => ['required']
        ]);

        $user = User::where($field, $account)->first();
        if (!Hash::check($password, $user->password)) {
            throw ValidationException::withMessages(['password' => '密码错误']);
        }

        Auth::login($user);

        return $this->successful('ok', $user);
    }

    public function logout(Request $request)
    {
        $id = auth()->id();
        $request->user()->currentAccessToken()->delete();
        return $this->successful('ok', $id);
    }

    public function register(RegisterRequest $request, User $user)
    {
        $user->username = $request->input('username');
        $user->password = Hash::make($request->input('password'));
        $user->save();
        $user->refresh();
        return $this->successful('ok', $user);
    }
}
